package com.woniuxy.sddfp.system.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniuxy.sddfp.common.constant.user.UserConstant;
import com.woniuxy.sddfp.common.exception.Assert;
import com.woniuxy.sddfp.common.model.dto.user.LoginDto;
import com.woniuxy.sddfp.common.model.dto.user.UserRegisterDto;
import com.woniuxy.sddfp.common.model.vo.user.LoginVo;
import com.woniuxy.sddfp.common.result.enums.impl.BusinessCode;
import com.woniuxy.sddfp.system.entity.User;
import com.woniuxy.sddfp.system.entity.UserDetail;
import com.woniuxy.sddfp.system.mapper.UserDetailMapper;
import com.woniuxy.sddfp.system.mapper.UserMapper;
import com.woniuxy.sddfp.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yellow docker
 * @since 2025-05-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserDetailMapper userDetailMapper;
    @Transactional(
            propagation = Propagation.REQUIRED,// 事务传播行为; 作用：对方法如何应用事务*      REQUIRED 默认值；当前运行方法必须有事务环境，如果没有，就创建事务; 如果有事务环境，就加入到当前事务
            rollbackFor = Exception.class/*默认回滚的是RuntimeException运行时期异常； 不会回滚检查异常；
 *                                         如果要回滚所有异常，指定rollbackFor = Exception.class*/
    )
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //校验手机号是否已经注册,用户名是否已经注册
        User phoneUser = this.getOne(Wrappers.lambdaQuery(User.class).eq(
                User::getPhone,userRegisterDto.getPhone()
        ));
        Assert.error(phoneUser != null, BusinessCode.PHONE_EXISTED);
        User nameUser = this.getOne(Wrappers.lambdaQuery(User.class).eq(
                User::getUserName,userRegisterDto.getUserName()
        ));
        Assert.error(nameUser != null, BusinessCode.USER_EXISTED);
        //保存用户
        User user = new User();
        user.setPhone(userRegisterDto.getPhone());
        user.setUserName(userRegisterDto.getUserName());
        //绑卡数据,后面使用
        //user.setRealName(userRegisterDto.getRealName());
        //user.setIdentityCode(userRegisterDto.getIdentityCode());


        //用hutool 工具进行加密(随机)
        String pwd = BCrypt.hashpw(userRegisterDto.getPwd());
        user.setPwd(pwd);
        //设置用户类别：个人用户
        user.setUserType(UserConstant.USER_TYPE_PERSONAL);
        user.setUserStatus(false);
        //保存用户
        this.save(user);


        //保存用户详情
        UserDetail userDetail = new UserDetail();
        userDetail.setId(user.getId());
        userDetail.setUserName(user.getUserName());
        userDetail.setPhone(user.getPhone());
        userDetail.setBorrowMoney(new BigDecimal(0));
        userDetail.setUserCode("UC_"+ UUID.randomUUID().toString().substring(0,10));
        userDetail.setCardBindStatus(false);

        //数据库保存用户详情
        userDetailMapper.insert(userDetail);
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        return loginDto.getIsPhoneLogin() ? UserPhoneLogin(loginDto):UserPwdLogin(loginDto);
    }
    /**
     * 账号密码登录
     * */
    private LoginVo UserPwdLogin(LoginDto loginDto) {
        /*User user = this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUserName ,loginDto.getLoginName())
        );*/
       /* Wrapper<User> dbUser = Wrappers.lambdaQuery(User.class)
                .eq(User::getPhone ,loginDto.getLoginName());*/
        //查询用户
        User user = getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName,loginDto.getLoginName()));
        // Assert.error(user==null,BusinessCode.USER_NOT_EXIST);
        //判断用户是否存在
        Assert.error(ObjectUtils.isEmpty(user),BusinessCode.USER_NOT_EXIST);//工具类
        //Assert.error(!BCrypt.checkpw(loginDto.getLoginSecret(),user.getPwd()),BusinessCode.USER_LOGIN_ERROR);
       // 判断密码是否正确
        Boolean flag = BCrypt.checkpw(loginDto.getLoginSecret(),user.getPwd());
        Assert.error(!flag,BusinessCode.USER_LOGIN_ERROR);
        //返回登录信息
        LoginVo  loginVo = LoginVo.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .phone(user.getPhone())
                .token("")
                .build();
        return loginVo;
    }
    /**
     * true手机号登录
     * */
    private LoginVo UserPhoneLogin(LoginDto loginDto) {
        return null;
    }
}
